<?php

declare(strict_types=1);

namespace app\controller\system\verify;

use app\BaseController;
use app\model\CartFuture;
use app\service\cart\FutureInquiryService;
use app\service\factory\ResponseFactory;
use app\validate\verify\FutureAdminUpdateValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class Inquiry extends BaseController
{
    public function index(FutureInquiryService $inquiryService): Response
    {
        if ($response = $this->denyIfNotAdmin()) {
            return $response;
        }

        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $filters = $this->request->only([
                'keyword',
                'status',
                'buyer_id',
                'buyer_org_id',
                'seller_id',
                'seller_org_id',
                'region_id',
                'assist_user_id',
            ], 'get');

            if (isset($filters['status']) && is_string($filters['status']) && strpos($filters['status'], ',') !== false) {
                $filters['status'] = array_map('intval', array_filter(explode(',', $filters['status'])));
            }

            $paginator = $inquiryService->paginateRecords(
                array_filter($filters, static fn($value) => $value !== null && $value !== ''),
                $page,
                $pageSize,
                ['buyer.profile', 'sellerOrg', 'product', 'assistUser.profile', 'region']
            );

            $items = $inquiryService->formatCollection($paginator->items(), 'admin');

            return json(ResponseFactory::paginated(
                $items,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, FutureInquiryService $inquiryService): Response
    {
        if ($response = $this->denyIfNotAdmin()) {
            return $response;
        }

        try {
            $record = $inquiryService->get($id);
            $formatted = $inquiryService->formatRecord($record->load(['buyer.profile', 'sellerOrg', 'product', 'assistUser.profile', 'region']), 'admin');

            return json(ResponseFactory::success($formatted));
        } catch (Throwable $e) {
            $code = $e->getCode() ?: 500;
            if ($code < 100 || $code >= 600) {
                $code = 500;
            }
            return json(ResponseFactory::error($e->getMessage(), $code));
        }
    }

    public function update(int $id, FutureInquiryService $inquiryService): Response
    {
        if ($response = $this->denyIfNotAdmin()) {
            return $response;
        }

        try {
            /** @var CartFuture|null $record */
            $record = CartFuture::find($id);
            if (!$record) {
                return json(ResponseFactory::error('询价单不存在', 404));
            }

            $payload = $this->request->put();
            $this->validate($payload, FutureAdminUpdateValidate::class . '.update');

            $updated = $inquiryService->adminUpdate($record, $payload);

            return json(ResponseFactory::success(
                $inquiryService->formatRecord($updated, 'admin'),
                '已更新'
            ));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    private function denyIfNotAdmin(): ?Response
    {
        $payload = (array) ($this->request->payload ?? []);
        $groups = $payload['groups'] ?? [];
        if (!is_array($groups) || !in_array('admin', $groups, true)) {
            return json(ResponseFactory::error('无访问权限', 403), 403);
        }

        return null;
    }
}
